package com.base.helper;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;

/**
 * @Author mzl.
 */
public class AesCrypt {

    /** 秘钥 */
    private static final String secretKey="enroll!@#2020";

    /**
     * aes加密
     * @param content 需要加密的内容
     * @return 加密后字符串
     */
    public static String aesEncrypt(String content) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(secretKey.getBytes("UTF-8"));
            kgen.init(128, random);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            /** 创建密码器 */
            Cipher cipher = Cipher.getInstance("AES");
            /** 初始化 */
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] buf = cipher.doFinal(content.getBytes("utf-8"));

            // 二进制转字符串
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < buf.length; i++) {
                String hex = Integer.toHexString(buf[i] & 0xFF);
                if (hex.length() == 1) {
                    hex = '0' + hex;
                }
                sb.append(hex.toUpperCase());
            }
            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException("aesEncrypt 加密异常!!!", e);
        }
    }

    /**
     * aes解密
     * @param hexStr  解密内容
     * @return 解密后字符串
     */
    public static String aesDecrypt(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] content = new byte[hexStr.length()/2];
        for (int i = 0;i< hexStr.length()/2; i++) {
            int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
            int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
            content[i] = (byte) (high * 16 + low);
        }

        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(secretKey.getBytes("UTF-8"));
            kgen.init(128, random);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            /** 创建密码器 */
            Cipher cipher = Cipher.getInstance("AES");
            /** 初始化 */
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] result = cipher.doFinal(content);
            return new String(result);
        } catch (Exception e) {
            throw new RuntimeException("aesDecrypt 解密异常!!!", e);
        }
    }

}
